"""
@Time ： 2024/4/29 14:17
@Auth ： czm
@File ：get_log.py
@IDE ：PyCharm
"""
import logging
from logging.handlers import RotatingFileHandler
import os
import time


class LogUtil:
    def get_project_path(self, project_name=None):
        """
        获取当前项目根路径
        :param project_name:
        :return: 根路径
        """
        project_name = 'EasyCityProject' if project_name is None else project_name
        project_path = os.path.abspath(os.path.dirname(__file__))
        # print(project_path)
        root_path = project_path[:project_path.find("{}\\".format(project_name)) + len("{}\\".format(project_name))]
        # print(project_path.find("{}\\".format(PROJECT_NAME)))
        # print(len("{}\\".format(PROJECT_NAME)))
        # print('当前项目名称：{}\r\n当前项目根路径：{}'.format(PROJECT_NAME, root_path))
        return root_path

    def get_logger(self):
        # 日志写入路径
        project_path = self.get_project_path()  # 获取项目跟目录
        strf_time = time.strftime("%Y%m%d")
        filename = project_path + '/log/' + strf_time + '.log'  # 定义日志存放路径及名称
        # file_handler = RotatingFileHandler(filename, maxBytes=20 * 1024 * 1024, backupCount=10, encoding='utf-8')
        file_handler = logging.handlers.TimedRotatingFileHandler(filename, when='midnight', interval=1, backupCount=7,
                                                                 encoding="UTF-8")

        # 第一步，创建一个logger日志器
        logger = logging.getLogger("logger")
        if not logger.handlers:
            # 设置log日志等级
            logger.setLevel(logging.INFO)
            # 创建日志处理器handler  控制台输出日志
            stream_handler = logging.StreamHandler()

            # 创建日志格式器 日志内容：时间  文件log.py 行号 [日志级别]  描述信息
            fmt = "%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s"
            log_format = logging.Formatter(fmt)

            # 添加控制台日志输出处理器，每个处理器都有各自的格式
            logger.addHandler(stream_handler)
            stream_handler.setFormatter(log_format)

            # 添加输出到文件日志处理器，并设置日志输出格式
            logger.addHandler(file_handler)
            file_handler.setFormatter(log_format)

        return logger


if __name__ == '__main__':
    logger = LogUtil()
    logger.get_logger().info("zhehsiyigerihzi ")
